<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card row_top">
      <el-tag type="warning" class="fit">
        <i class="el-icon-warning"></i>注意 ：只允许为第三级分类设置相关参数!
      </el-tag>
      <!--选择产品-->
      <div class="row_top">
        选择商品分类:
        <el-cascader v-model="bid" :options="lianbor" :props="propt" @change="hangde" clearable></el-cascader>
      </div>
      <!--Tab栏-->
      <el-row class="row_top">
        <el-tabs v-model="activeName" @tab-click="handleTab">
          <el-button
            type="primary"
            size="small"
            @click="addRole()"
            class="row_top"
            :disabled="Tabled"
          >添加参数</el-button>
          <!--静态数据的渲染-->
          <el-tab-pane label="动态参数" name="many" :disabled="Tabled">
            <el-table :data="Tabdata" border style="width: 100%">
              <!--展开行-->
              <el-table-column type="expand">
                <template slot-scope="props">
                  <!--tab标签-->
                  <el-tag
                    v-for="(tag,ind) in props.row.attr_vals"
                    :key="ind"
                    closable
                    class="le"
                    @close="deletab(props.row,ind)"
                  >{{tag}}</el-tag>
                  <!--添加tab标签对表单-->
                  <el-input
                    class="input-new-tag"
                    v-if="props.row.inputVisible"
                    v-model="props.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(props.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <!--操作-->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" @click="icont(scope.row)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="icDele(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
           <!--静态数据的渲染-->
          <el-tab-pane label="静态参数" name="only" :disabled="Tabled">
            <el-table :data="Tabdata" border style="width: 100%">
              <!--展开行-->
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-tag
                    v-for="(tag,ind) in props.row.attr_vals"
                    :key="ind"
                    closable
                    class="le"
                  >{{tag}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="props.row.inputVisible"
                    v-model="props.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(props.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" @click="icont(scope.row)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="icDele(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
    <!--添加参数-->
    <el-dialog
      :title="activeName=='many'?'添加动态属性':'添加静态属性'"
      :visible.sync="labalvisible"
      width="50%"
      @close="redfix('labalForm')"
    >
      <!--内容区-->
      <el-form
        :model="labaldata"
        :rules="labalrules"
        ref="labalForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="activeName=='many'?'动态属性':'静态属性'" prop="attr_name">
          <el-input v-model="labaldata.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="labalvisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改对话框-->
    <el-dialog
      :title="activeName=='many'?'修改动态属性':'修改静态属性'"
      :visible.sync="updatvisible"
      width="50%"
      @close="redfix('updatref')"
    >
      <!--内容区-->
      <el-form
        :model="updatdata"
        :rules="labalrules"
        ref="updatref"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="activeName=='many'?'修改属性':'修改属性'" prop="attr_name">
          <el-input v-model="updatdata.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updatvisible = false">取 消</el-button>
        <el-button type="primary" @click="updatRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dele from "../delet.js";
export default {
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.createCate();
  },
  data: () => {
    return {
      //级联选择器的内容
      lianbor: [],
      //级联选择器选中后存储 id 值
      bid: [],
      //级联列表规则
      propt: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //Tab选中的是静动态
      activeName: " ",
      //Tab栏是否禁用
      Tabled: true,
      //Tab栏的数据的存储
      Tabdata: [],
      //Tab的显示与隐藏
      labalvisible: false,
      //添加参数
      labaldata: {
        attr_name: ""
      },
      //添加与修改的数据验证规则
      labalrules: {
        attr_name: [
          { required: true, message: "请输入值" },
          { min: 2, message: "请输入最少2位数", tirgger: "blur" }
        ]
      },
      //修改对话框显示与隐藏
      updatvisible: false,
      //修改对话框数据
      updatdata: {
        attr_name: ""
      },
      //（修改）各自类的属性值id
      attr_Id: "",
    };
  },
  methods: {
    //Tab标签的添加
  async handleInputConfirm(row){
      //判断，如果用户没有输入文本值，不给予添加
      let inputValue = row.inputValue;
      console.log(row.inputValue);
      if(inputValue.trim().length<1){
        row.inputVisible = false;
        row.inputValue = '';
        return false;
      }
      row.attr_vals.push(inputValue.trim());
      this.tabinit(row);
    },
    //tab标签对的删除添加公共函数
    async tabinit(row){
       let {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
      {
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')
      });
      if(res.meta.status!=200){
        console.log(res.meta);
        return this.$message.error('添加失败');
      }
      this.$message.success('添加成功');
      //如果用户有输入值的话，那么为其添加
        row.inputVisible = false;
        row.inputValue = '';
    },
     //Tab标签对的删除
    deletab(row,ind){
      row.attr_vals.splice(ind,1);
      this.tabinit(row);
    },
    //得到焦点
    showInput(row){
      row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //级联选择器数据的请求
    async createCate() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        console.log(res.meta);
        return false;
      }
      this.lianbor = res.data;
      //console.log(this.lianbor);
    },
    //Tab栏发生变化时
    handleTab() {
      this.hangde();
      //得到目前选中的那个Tab名称
      //console.log(this.activeName);
    },
    //静动态参数的请求（当级联选择器发生变化时）
    async hangde() {
      //判断是否有选中到底
      if (this.bid.length != 3) {
        this.bid = [];
        //清空默认选中
        this.activeName = " ";
        //禁用Tab栏
        this.Tabled = true;
        return;
      }
      //开启tab栏
      this.Tabled = false;
      //默认选中一个动态参数
      if (this.activeName == " ") {
        this.activeName = "many";
      }
      //当我们选中参数后
      //发送ajax请求
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status != 200) {
        console.log(res.meta);
        return false;
      }
      //下拉列表的数据标签的数据循环(为了下拉表格相互的数据互不影响)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals != "" ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = ""
      });


      console.log(res.data);
      //当我们请求完毕的时候，往静动态参数表里面插入参数
      this.Tabdata = res.data;
      // console.log(this.Tabdata.attr_id);
    },
    //添加参数框
    addRole() {
      //弹出表单行
      this.labalvisible = true;
      //验证规则
    },
    //确认添加参数框(未完善);
    AddRole() {
      //console.log("确认添加");
      //首先判断其表单是否为空
      this.$refs.labalForm.validate(async item => {
        if (!item) {
          return this.$message.error("请输入文本值");
        }
        //参数名称
        //[静态，动态]
        //如果是动态，可以多添加值，以逗号分格 []
        let { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.labaldata.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status != 201) {
          console.log(res.meta);
          return this.$message.error("创建失败");
        }
        this.labalvisible = false;
        this.hangde();
      });
      //成功，发送请求，
      //判断是否添加成功
      //关闭弹框
      //初始化页面
    },
    //重置确认添加表单
    redfix(ref) {
      this.$refs[ref].resetFields();
    }, 
    //修改框的弹出
    async icont(id) {
      //绑定属性id
      this.attr_Id = id.attr_id;
      let {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id.attr_id}`,
        { params: { attr_sel: `${this.activeName}` } }
      );

      if (res.meta.status != 200) {
        console.log(res.meta);
        return this.$message.error("失败");
      }
      //得到当前用户的值，并渲染到对话框上
      this.updatdata.attr_name = res.data.attr_name;
      //弹出修改对话框
      this.updatvisible = true;
    },
    //确认修改
    updatRole() {
      this.$refs.updatref.validate(async item => {
        //表单预验证
        if (!item) {
          return this.$message.error("请输入文本值");
        }
        let { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.attr_Id}`,
          {
            attr_name: this.updatdata.attr_name,
            attr_sel: this.activeName,
            attr_vals: "attr_name"
          }
        );
        if (res.meta.status != 200) {
          console.log(res.data);
          return this.$message.error("错误");
        }
        this.$message.success("修改成功");
        //初始化函数
        this.hangde();
        //关闭弹框
        this.updatvisible = false;
      });
    },
    //删除操作
    async icDele(row) {
      let a = await dele.dele(this.$confirm);
      console.log(row);
      //如果用户点击了确定，那么发送ajax请求
      if (a == "confirm") {
        let { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${row.attr_id}`
        );
        if (res.meta.status != 200) {
          console.log(res.meta);
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        this.hangde();
      } else {
        return this.$message.success("取消删除");
      }
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.bid.length != 3) {
        return true;
      }
      return false;
    },
    //分类的id
    cateId() {
      if (this.bid.length == 3) {
        return this.bid[2];
      }
      return null;
    }
  },
  mounted:function(){
    //document.getElementsByClassName('el-cascader-panel')[0].style.height = '200px';
  }
};
</script>
<style scoped lang="less">
.fit {
  width: 100%;
  font-size: 15px;
}
.row_top {
  margin: 10px 0;
}
.le {
  margin: 5px;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
}

.el-popper .el-cascader-panel{
  height: 200px!important;
}

/* @import url(); 引入css类 */
</style>